package com.laowang.project.system.controller;

import java.math.BigDecimal;
import java.util.Date;
import java.util.List;
import java.util.Map;
import java.util.concurrent.TimeUnit;
import java.util.stream.Collectors;

import com.alibaba.fastjson.JSONObject;
import com.github.pagehelper.PageHelper;
import com.laowang.common.exception.CustomException;
import com.laowang.common.utils.SecurityUtils;
import com.laowang.common.utils.StringUtils;
import com.laowang.framework.web.page.TableDataInfoMy;
import com.laowang.project.system.domain.*;
import com.laowang.project.system.domain.vo.Details;
import com.laowang.project.system.domain.vo.WxUserVo;
import com.laowang.project.system.mapper.SysRoleMapper;
import com.laowang.project.system.service.*;
import io.swagger.annotations.Api;
import io.swagger.annotations.ApiOperation;

import org.springframework.security.access.prepost.PreAuthorize;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.web.bind.annotation.GetMapping;
import org.springframework.web.bind.annotation.PostMapping;
import org.springframework.web.bind.annotation.PutMapping;
import org.springframework.web.bind.annotation.DeleteMapping;
import org.springframework.web.bind.annotation.PathVariable;
import org.springframework.web.bind.annotation.RequestBody;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RestController;
import com.laowang.framework.aspectj.lang.annotation.Log;
import com.laowang.framework.aspectj.lang.enums.BusinessType;

import org.springframework.web.bind.annotation.*;
import com.laowang.framework.web.controller.BaseController;
import com.laowang.framework.web.domain.AjaxResult;
import com.laowang.common.utils.poi.ExcelUtil;
import com.laowang.framework.web.page.TableDataInfo;
import oshi.jna.platform.mac.SystemB;
import tk.mybatis.mapper.genid.GenId;

/**
 * 车友活动Controller
 *
 * @author laowang
 * @date 2023-04-24
 */
@Api(tags = "车友活动接口")
@RestController
@RequestMapping("/activity")
public class MyCyhActivityController extends BaseController {
    @Autowired
    private MyCyhActivityService myCyhActivityService;

    @Autowired
    private WxUserService wxUserService;

    @Autowired
    private MyCyhActivityCodeService myCyhActivityCodeService;

    @Autowired
    private MyCyhVipAuthorityService myCyhVipAuthorityService;

    @Autowired
    private SysRoleMapper sysRoleMapper;

    @Autowired
    private MyCyhCarGroupService myCyhCarGroupService;

    @Autowired
    private MyCyhVipService myCyhVipService;

    @Autowired
    private MyCyhActivitySignService myCyhActivitySignService;

    /**
     * 查询车友活动列表
     */
    @ApiOperation(value = "小程序端 创建活动",notes = "")
    @PostMapping("/web/add")
    public AjaxResult webAdd(@RequestBody MyCyhActivity myCyhActivity) {

        myCyhActivityService.insertMyCyhActivityWeb(myCyhActivity);
        return AjaxResult.success("操作成功");
    }

    /**
     * 查询车友活动列表
     */
    @ApiOperation(value = "小程序端 查询车友活动列表",notes = "")
    @GetMapping("/web/list")
    public TableDataInfoMy webList(MyCyhActivity myCyhActivity) {
        startPage();
        myCyhActivity.setAuditStatus(1);
        List<MyCyhActivity> list = myCyhActivityService.selectMyCyhActivityListWeb(myCyhActivity);
        return getDataTableMy(list);
    }

    @ApiOperation(value = "小程序端 自己参加的活动",notes = "")
    @GetMapping("/web/my")
    public TableDataInfoMy myList() {
        startPage();
        Integer mid = SecurityUtils.getLoginUser().getWxUser().getMid();
        List<MyCyhActivity> list = myCyhActivityService.selectMyCyhActivitymyList(mid);
        return getDataTableMy(list);
    }



    /**
     * 活动详情
     */
    @ApiOperation(value = "小程序端 活动详情(活动介绍)",notes = "")
    @GetMapping("/web/{id}")
    public AjaxResult webId(@PathVariable("id") Integer id) {
        MyCyhActivity myCyhActivity = myCyhActivityService.selectMyCyhActivityByIdWeb(id);
        MyCyhActivityCode myCyhActivityCode = new MyCyhActivityCode();
        myCyhActivityCode.setActivityId(id);
        myCyhActivityCode.setIsEnable(1);//上架
        //List<MyCyhActivityCode> myCyhActivityCodes = myCyhActivityCodeService.selectMyCyhActivityCodeList(myCyhActivityCode);

        //Integer mid = SecurityUtils.getLoginUser().getWxUser().getMid();
        //WxUser wxUser = wxUserService.selectWxUserById(mid);

        List<MyCyhCarGroup> myCyhCarGroups = myCyhCarGroupService.selectMyCyhCarGroupListWeb(null);
        Map<Integer, String> collect = myCyhCarGroups.stream().collect(Collectors.toMap(MyCyhCarGroup::getId, MyCyhCarGroup::getGroupName));

        /*if (wxUser == null ){
            return AjaxResult.error(401,"请重新登录");
        }*/
        if (myCyhActivity != null){
            List<WxUserVo> users = myCyhActivity.getUsers();
            if (myCyhActivity.getIsFree().equals(0)){//0收费
                //1免费
                users = users.stream().filter(wxUserVo -> wxUserVo.getIsPay().equals(1)).collect(Collectors.toList());
                for (WxUserVo user : users) {

                    if (StringUtils.isNotEmpty(user.getGroupName()) && collect.containsKey(Integer.valueOf(user.getGroupName())) ){
                        user.setGroupName(collect.get(Integer.valueOf(user.getGroupName())));
                    }

                }

                myCyhActivity.setUsers(users);

                /*Integer discountType = myCyhActivity.getDiscountType();
                if (discountType !=null){
                    if (discountType == 1){
                        if (wxUser.getVipLevel() != null && wxUser.getExpireTime() !=null && wxUser.getExpireTime().after(new Date())){
                            // `discount_type` int DEFAULT NULL COMMENT '1固定会员折扣,2会员等级折扣',
                            BigDecimal fixDisPrice = myCyhActivity.getFixDisPrice();
                            if (fixDisPrice !=null){
                                BigDecimal price = myCyhActivity.getFee();
                                if (price.compareTo(fixDisPrice)>0){
                                    BigDecimal disprice = price.subtract(fixDisPrice);
                                    myCyhActivity.setFee(disprice);
                                }
                            }
                        }


                    }else if (discountType == 2){
                        //会员等级折扣
                        BigDecimal decimal =new BigDecimal(0);

                        if (wxUser.getStockHolder() != null && wxUser.getStockHolder().equals(1)) {
                            //是合伙人
                            decimal = myCyhActivity.getPartnerDiscount();

                        } else {

                            if (wxUser.getPromoDor() != null && wxUser.getPromoDor().equals(1) && wxUser.getExpireTime1() != null && wxUser.getExpireTime1().after(new Date())) {
                                //是推荐管
                                decimal = myCyhActivity.getPromoDiscount();

                            } else {

                                if (wxUser.getVipLevel() != null && wxUser.getExpireTime() != null && wxUser.getExpireTime().after(new Date())) {
                                    //是会员
                                    String details = myCyhActivity.getDetails();

                                    if (StringUtils.isNotEmpty(details)){
                                        Details details1 = JSONObject.parseObject(details, Details.class);
                                        Integer vipLevel = wxUser.getVipLevel();
                                        if (vipLevel.equals(1)){
                                            decimal = details1.getOne();
                                        }else if (vipLevel.equals(2)){
                                            decimal = details1.getTwo();
                                        }else if (vipLevel.equals(3)){
                                            decimal = details1.getThree();
                                        }else if (vipLevel.equals(4)){
                                            decimal = details1.getFour();
                                        }else if (vipLevel.equals(5)){
                                            decimal= details1.getFive();
                                        }
                                    }

                                } else {

                                }
                            }
                        }
                        if (decimal.compareTo(new BigDecimal(0)) > 0){
                            BigDecimal price2 = myCyhActivity.getFee();
                            int price1 = price2.multiply(decimal ).divide(new BigDecimal(100)).intValue();
                            myCyhActivity.setFee1(new BigDecimal(price1) );
                        }
                    }
                }*/
            }
            //myCyhActivity.setMyCyhActivityCodes(myCyhActivityCodes);
        }
        return AjaxResult.success("操作成功",myCyhActivity);
    }

    @ApiOperation(value = "小程序端 活动详情",notes = "")
    @GetMapping("/web/detail/{id}")
    public AjaxResult webDetail(@PathVariable("id") Integer id) {

        MyCyhActivity myCyhActivity = myCyhActivityService.selectMyCyhActivityById(id);

        Integer mid = SecurityUtils.getLoginUser().getWxUser().getMid();
        WxUser wxUser = wxUserService.selectWxUserById(mid);

        if (wxUser == null ){
            return AjaxResult.error(401,"请重新登录");
        }
        if (myCyhActivity != null){

            if (myCyhActivity.getIsFree().equals(0)){//0收费

                Integer discountType = myCyhActivity.getDiscountType();
                if (discountType !=null){
                    if (discountType == 1){
                        if (wxUser.getVipLevel() != null && wxUser.getExpireTime() !=null && wxUser.getExpireTime().after(new Date())){
                            // `discount_type` int DEFAULT NULL COMMENT '1固定会员折扣,2会员等级折扣',
                            BigDecimal fixDisPrice = myCyhActivity.getFixDisPrice();
                            if (fixDisPrice !=null){
                                BigDecimal price = myCyhActivity.getFee();
                                if (price.compareTo(fixDisPrice)>0){
                                    BigDecimal disprice = price.subtract(fixDisPrice);
                                    myCyhActivity.setFee(disprice);
                                }
                            }
                        }


                    }else if (discountType == 2){
                        //会员等级折扣
                        BigDecimal decimal =new BigDecimal(0);

                        if (wxUser.getStockHolder() != null && wxUser.getStockHolder().equals(1)) {
                            //是合伙人
                            decimal = myCyhActivity.getPartnerDiscount();

                        } else {

                            if (wxUser.getPromoDor() != null && wxUser.getPromoDor().equals(1) && wxUser.getExpireTime1() != null && wxUser.getExpireTime1().after(new Date())) {
                                //是推荐管
                                decimal = myCyhActivity.getPromoDiscount();

                            } else {

                                if (wxUser.getVipLevel() != null && wxUser.getExpireTime() != null && wxUser.getExpireTime().after(new Date())) {
                                    //是会员
                                    String details = myCyhActivity.getDetails();

                                    if (StringUtils.isNotEmpty(details)){
                                        Details details1 = JSONObject.parseObject(details, Details.class);
                                        Integer vipLevel = wxUser.getVipLevel();
                                        if (vipLevel.equals(1)){
                                            decimal = details1.getOne();
                                        }else if (vipLevel.equals(2)){
                                            decimal = details1.getTwo();
                                        }else if (vipLevel.equals(3)){
                                            decimal = details1.getThree();
                                        }else if (vipLevel.equals(4)){
                                            decimal = details1.getFour();
                                        }else if (vipLevel.equals(5)){
                                            decimal= details1.getFive();
                                        }
                                    }

                                } else {

                                }
                            }
                        }
                        if (decimal.compareTo(new BigDecimal(0)) > 0){
                            BigDecimal price2 = myCyhActivity.getFee();
                            int price1 = price2.multiply(decimal ).divide(new BigDecimal(100)).intValue();
                            myCyhActivity.setFee1(new BigDecimal(price1) );
                        }
                    }
                }
            }
            //myCyhActivity.setMyCyhActivityCodes(myCyhActivityCodes);
        }

        return AjaxResult.success(myCyhActivity);
    }


    @ApiOperation(value = "小程序端 参与车友",notes = "")
    @GetMapping("/web/users/{id}")
    public TableDataInfoMy webUsers(@PathVariable("id") Integer id,Integer pageNum,Integer pageSize,Integer userId) {


        MyCyhActivity myCyhActivity = myCyhActivityService.selectMyCyhActivityById(id);
        if (myCyhActivity == null){
            throw  new CustomException("活动信息不存在");
        }

        //Integer mid = SecurityUtils.getLoginUser().getWxUser().getMid();
        if (pageNum !=  null && pageSize != null){

            PageHelper.startPage(pageNum,pageSize);
        }
        List<WxUserVo> users =  myCyhActivitySignService.selectUserById(id, userId);

        return getDataTableMy(users);
    }



    /**
     * 查询车友活动列表
     */
    @ApiOperation(value = "查询车友活动列表",notes = "")
    @PreAuthorize("@ss.hasPermi('my:activity:list')")
    @GetMapping("/list")
    public TableDataInfo list(MyCyhActivity myCyhActivity) {
        Long userId = SecurityUtils.getLoginUser().getUser().getUserId();

        //不是管理员
        if (!userId.equals(1L)  ){
            List<SysRole> sysRoles = sysRoleMapper.selectRolePermissionByUserId(userId);
            // 是 活动管理者
            Boolean b = sysRoles.stream().anyMatch(sysRole -> sysRole.getRoleKey().equals("activityManager"));
            if (b){
                myCyhActivity.setCreateBy(userId);
            }
        }
        startPage();
        List<MyCyhActivity> list = myCyhActivityService.selectMyCyhActivityList(myCyhActivity);
        return getDataTable(list);
    }

    /**
     * 导出车友活动列表
     */
    @ApiOperation(value = "导出车友活动列表",notes = "")
    @PreAuthorize("@ss.hasPermi('my:activity:export')")
    @Log(title = "车友活动", businessType = BusinessType.EXPORT)
    @GetMapping("/export")
    public AjaxResult export(MyCyhActivity myCyhActivity) {
        List<MyCyhActivity> list = myCyhActivityService.selectMyCyhActivityList(myCyhActivity);
        ExcelUtil<MyCyhActivity> util = new ExcelUtil<MyCyhActivity>(MyCyhActivity.class);
        return util.exportExcel(list, "activity");
    }

    /**
     * 获取车友活动详细信息
     */
    @ApiOperation(value = "获取车友活动详细信息",notes = "")
    @PreAuthorize("@ss.hasPermi('my:activity:query')")
    @GetMapping(value = "/{id}")
    public AjaxResult getInfo(@PathVariable("id") Integer id) {
        return AjaxResult.success(myCyhActivityService.selectMyCyhActivityById(id));
    }

    /**
     * 新增车友活动
     */
    @ApiOperation(value = "新增车友活动",notes = "")
    @PreAuthorize("@ss.hasPermi('my:activity:add')")
    @Log(title = "车友活动", businessType = BusinessType.INSERT)
    @PostMapping
    public AjaxResult add(@RequestBody MyCyhActivity myCyhActivity) {
        Long userId = SecurityUtils.getLoginUser().getUser().getUserId();
        //不是管理员
        if (!userId.equals(1L)  ){
            List<SysRole> sysRoles = sysRoleMapper.selectRolePermissionByUserId(userId);
            // 是 活动管理者
            Boolean b = sysRoles.stream().anyMatch(sysRole -> sysRole.getRoleKey().equals("activityManager"));
            if (b){
                myCyhActivity.setCreateBy(userId);
            }
        }

        return toAjax(myCyhActivityService.insertMyCyhActivity(myCyhActivity));
    }

    /**
     * 修改车友活动
     */
    @ApiOperation(value = "修改车友活动",notes = "")
    @PreAuthorize("@ss.hasPermi('my:activity:edit')")
    @Log(title = "车友活动", businessType = BusinessType.UPDATE)
    @PutMapping
    public AjaxResult edit(@RequestBody MyCyhActivity myCyhActivity) {
        return toAjax(myCyhActivityService.updateMyCyhActivity(myCyhActivity));
    }

    /**
     * 删除车友活动
     */
    @ApiOperation(value = "删除车友活动",notes = "")
    @PreAuthorize("@ss.hasPermi('my:activity:remove')")
    @Log(title = "车友活动", businessType = BusinessType.DELETE)
	@DeleteMapping("/{ids}")
    public AjaxResult remove(@PathVariable Integer[] ids) {
        return toAjax(myCyhActivityService.deleteMyCyhActivityByIds(ids));
    }
}
